<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/18 14:56
 * @version
 */
namespace Modules\Service\Logic;

use App\Models\Address;
use App\Models\CompanyOilCard;
use App\Models\Configure;
use App\Models\Coupon;
use App\Models\ExpressConfig;
use App\Models\Goods;
use App\Models\MobileRecharge;
use App\Models\MobileRechargeOrder;
use App\Models\MobileRechargeOrderDetail;
use App\Models\OilCard;
use App\Models\OilCardExpress;
use App\Models\Pay;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\RechargeOrderDetail;
use App\Models\ShopOrder;
use App\Models\ShopOrderDetail;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Token\Facades\Token;

class OilcardOrderLogic extends BaseLogic{

    //充值支付
    public static function oilOrderAndPay($oilCardId,$mobile,$channel,$openid,$rechargeId,$payType,$rechargeAmount,$couponId,$userData,$version,$platform='ios'){
        try {
            DB::beginTransaction();
            Log::info("这里获取的有卡ID是：".$oilCardId);
            //格式化钱符号
            $rechargeAmount = formatPrice($rechargeAmount);
            $amount = $rechargeAmount;
            //定义参数
            //查询充值套餐
            if ($rechargeId) {
                if ($channel=='oil_recharge') {
                    //查询套餐
                    $rechargeData = Recharge::find($rechargeId);
                }else{
                    //插叙套餐
                    $rechargeData = MobileRecharge::find($rechargeId);
                }
                if (!$rechargeData) return fail(1013, "充值套餐不存在");
                //赋值
                $discount = $rechargeData->discount;
                $months = $rechargeData->months;
                $type = 1;
                //计算套餐价格
                $payAmount = formatPrice(($rechargeAmount * $rechargeData->months) * $rechargeData->discount);
            }else{
                //直充修正充值金额错误
                if ($rechargeAmount>0 && $rechargeAmount<=30){
                    $amount = 30;
                }elseif($rechargeAmount>30 && $rechargeAmount<=50){
                    $amount = 50;
                }elseif ($rechargeAmount>50 && $rechargeAmount<=100){
                    $amount = 100;
                }elseif($rechargeAmount>100 && $rechargeAmount<=200){
                    $amount = 200;
                }elseif ($rechargeAmount>200 && $rechargeAmount<=300){
                    $amount = 300;
                }elseif($rechargeAmount>300 && $rechargeAmount<=400){
                    $amount = 400;
                }elseif ($rechargeAmount>400 && $rechargeAmount<=500){
                    $amount = 500;
                }elseif ($rechargeAmount>500 && $rechargeAmount<=1000){
                    $amount = 1000;
                }elseif ($rechargeAmount>1000 && $rechargeAmount<=2000){
                    $amount = 2000;
                }elseif ($rechargeAmount>4000 && $rechargeAmount<=5000){
                    $amount = 5000;
                }else{
                    $amount = $rechargeAmount;
                }
                $discount = Configure::rechargeDiscount();
                $payAmount = formatPrice($amount * Configure::rechargeDiscount());
                $type = 2;
                $months = 1;
            }
            //查询优惠券信息
            if ($couponId) {
                $couponData = UserCoupon::find($couponId);
                if (!$couponData) return fail(1016, "无效的优惠券,请重新选择");
                if($couponData->status > 1) return fail(1016,'优惠券无效');
                $couponAmount = $couponData->amount;
                //验证优惠券的合法性
                $couponInfo = Coupon::query()->find($couponData->coupon_id);
                if(!$couponInfo) return fail(1016,'无效的优惠券');
                //验证消费金额
                $totalAmount = $amount * $months;
                if($couponInfo->min_amount > 0 && $totalAmount < $couponInfo->min_amount){
                    Log::error('coupon amount error:' . $couponData->user_id . '-' . $couponData->id . ':' . $totalAmount . '<' . $couponInfo->min_amount);
                    return fail(1016,'优惠券无效,充值金额不满足使用条件');
                }
                //验证月数
                if($months < $couponInfo->months){
                    Log::error('coupon months error:' . $couponData->user_id . '-' . $couponData->id . ':' . $months . '<' . $couponInfo->months);
                    return fail(1016,'优惠券无效,充值套餐月数必须不能小于' . $couponInfo->months);
                }


                //验证渠道
                if($channel != $couponInfo->channel){
                    return fail(1016,'优惠券无效');
                }

                //冻结优惠券
                $couponData->status = 4;
                $couponData->used_at = Carbon::now();
                $couponData->save();
                //查询用户充值记录
                if (!$mobile && $oilCardId) {
                    $rechargeRecords = RechargeOrder::where("user_id", $userData->id)->first();
                }else{
                    $rechargeRecords = MobileRechargeOrder::where("user_id",$userData->id)->first();
                }
                if ($rechargeRecords) {
                    //判断是否为新人专享优惠券
                    if ($couponData->new_exclusive == 1) {
                        return fail(1017, "优惠券为新人专享,请重新选择");
                    }
                }
                //计算价格
                $payAmount = $payAmount - $couponAmount;
                if($payAmount <= 0){
                    return fail(1016,'订单错误');
                }
            }

            if ($channel=="oil_recharge"){
                //查询油卡数据
//                Log::info("这里打印的版本信息是:".$version);
//                if ($platform=='android' && compareAppVersion('1.2.0',$version)=='lt'){
//                    Log::info("版本大于1.1.4");
//                    $oilCardData = OilCard::where("user_id",$userData->id)->where("card_no",$oilCardId)->first();
//                }else {
//                    Log::info("正常");
                    $oilCardData = OilCard::find($oilCardId);
//                }
                if (!$oilCardData) return fail(1012, "油卡不存在");
                //判断油卡是否是自家公司下的副卡
                $companyData = CompanyOilCard::where("card_no",$oilCardData->card_no)->count();
                if ($companyData){
                    $recharge_mode = 2;
                }else{
                    $recharge_mode = 1;
                }
                //卡号
                $card_no = $oilCardData->card_no;
                //油卡类型
                $card_type = $oilCardData->type;

                //实例化对象
                $order = new RechargeOrder();
                $order->order_sn = orderSn();
                $order->user_id = $userData->id;
                $order->recharge_id = $rechargeId;
                $order->coupon_id = $couponId;
                $order->type = $type;
                $order->recharge_amount = $amount;
                $order->pay_amount = $payAmount;
                $order->oil_card_id = $oilCardData->id;
                $order->discount = $discount;
                $order->months = $months;
                $order->user_mobile = $userData->mobile;
                $order->card_type = $card_type;
                $order->card_no = $card_no;
                $order->shop_order_id = 0;
                $order->status = 0;
                $order->recharge_mode = $recharge_mode;
                $order->created_at = Carbon::now();
            }else{
                //实例化对象
                $order = new MobileRechargeOrder();
                $order->order_sn = orderSn();
                $order->user_id = $userData->id;
                $order->recharge_id = $rechargeId;
                $order->coupon_id = $couponId;
                $order->type = $type;
                $order->recharge_amount = $amount;
                $order->pay_amount = $payAmount;
                $order->mobile = $mobile;
                $order->discount = $discount;
                $order->months = $months;
                $order->status = 0;
                $order->created_at = Carbon::now();
            }

            //创建支付
            $pay = new Pay();
            $pay->payment_method = $payType;
            $pay->user_id = $userData->id;
            if ($channel=='oil_recharge') {
                $pay->pay_sn = Pay::makeYouKaPaySN();
            }else{
                $pay->pay_sn = Pay::makeHuaFeiPaySN();
            }
            $pay->amount = $payAmount;
            $pay->save();

            $order->pay_id = $pay->id;//支付流水id
            $order->save();

            $response = [
                'order_id' => $order->id,
                'payment_method' => $payType,
                'pay_info' => null,
            ];
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payType == 'alipay') {
                $response['pay_info'] = Pay::alipay($pay);
            }
            if ($payType == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp($pay,$version);
            }
            if ($payType == 'weixin') {
                $response['weixin'] = Pay::weixin($pay, $openid);
            }

            DB::commit();
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            DB::rollBack();
            return fail(500,"系统错误");
        }
    }

    //订单再次支付
    public static function oilOrderAgainPay($id,$payType,$channel,$openid){
        try {
            if ($channel=='oil_recharge') {
                //查询订单
                $order = RechargeOrder::find($id);
            }
            if ($channel=='mobile_recharge'){
                $order = MobileRechargeOrder::find($id);
            }
            //查询用户信息
            $user = User::find(Token::data('id'));
            //更改支付方式
            $pay = $order->pay;
            $pay->payment_method = $payType;

            $response = [
                'order_id' => $order->id,
                'payment_method' => $payType,
                'pay_info' => null,
            ];
            //支付序号
            if ($pay->pay_sn) {
                if ($channel=='oil_recharge') {
                    $pay->pay_sn = Pay::makeYouKaPaySN();
                } elseif ($channel=='mobile_recharge') {
                    $pay->pay_sn = Pay::makeHuaFeiPaySN();
                }
            }
            $pay->save();
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($payType == 'alipay') {
                $response['pay_info'] = Pay::alipay_num($pay);
            } elseif ($payType == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_num($pay);
            } elseif ($payType == 'weixin') {
                $response['weixin'] = Pay::weixin_num($pay, $openid);
            } else {
                return fail(201,"无效的支付方式");
            }
            return success($response);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"发起支付失败");
        }
    }

    //计算运费
    public static function oilOrderExpress($rechargeId,$amount){
        try{
            //查询套餐
            $rechargeData = Recharge::find($rechargeId);
            if (!$rechargeData){
                $expressFee = 10;
            }else {
                if ($rechargeData->months>=3 && $amount*$rechargeData->months>=2000){
                    $expressFee = 0;
                }else{
                    $expressFee = 10;
                }
//                $expressFeeData = ExpressConfig::where("amount", "<=", $amount)->orderBy("amount", "desc")->first();
//                if ($expressFeeData) {
//                    //运费
//                    $expressFee = $expressFeeData->express_fee;
//                }else{
//                    return fail(1031,"未设置配送金额");
//                }
            }
            //油卡状态
            $oilCard = config('recharge.oil_card');
            //剩余卡数
            $SinopecNum = CompanyOilCard::where("status",0)->where("type",1)->count();
            $PetroChinaNum = CompanyOilCard::where("status",0)->where("type",2)->count();
            $oilCard['Sinopec_total'] = $SinopecNum;
            $oilCard['PetroChina_total'] = $PetroChinaNum;
            $oilCard['express_fee'] = $expressFee;
            $oilCard['express_text'] = "充值3月及以上套餐且金额满2000包邮";
            return success($oilCard);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //领取油卡
    public static function getOilCardByNewUser($userId,$addressId,$rechargeId,$coupon_id,$pay_type,$amount,$openid,$type){
        try{
            //查询用户
            $userData = User::find($userId);
            if (!$userData)return fail(1014,"用户不存在");
            //查询收货地址
            $addressData = Address::find($addressId);
            if (!$addressData)return fail(1018,"收货地址不存在");
            //查询充值套餐
            $rechargeData = Recharge::find($rechargeId);
            if (!$rechargeData)return fail(1013,"油卡套餐不存在");
            //计算支付金额
            $payAmount = ($amount * $rechargeData->months) * $rechargeData->discount;
            //减去优惠券
            if ($coupon_id){
                $couponData = UserCoupon::find($coupon_id);
                if (!$couponData) return fail(1016, "无效的优惠券,请重新选择");
                if($couponData->status > 1) return fail(1016,'优惠券无效');
                $couponAmount = $couponData->amount;
                //验证优惠券的合法性
                $couponInfo = Coupon::query()->find($couponData->coupon_id);
                if(!$couponInfo) return fail(1016,'无效的优惠券');
                //验证消费金额
                $totalAmount = $amount * $rechargeData->months;
                if($couponInfo->min_amount > 0 && $totalAmount < $couponInfo->min_amount){
                    Log::error('coupon error:' . $couponData->user_id . '-' . $couponData->id . ':' . $totalAmount . '<' . $couponInfo->min_amount);
                    return fail(1016,'优惠券无效,充值金额不满足使用条件');
                }

                //冻结优惠券
                $couponData->status = 4;
                $couponData->used_at = Carbon::now();
                $couponData->save();
                //查询用户充值记录
                $rechargeRecords = RechargeOrder::where("user_id", $userData->id)->first();
                if ($rechargeRecords) {
                    //判断是否为新人专享优惠券
                    if ($couponData->new_exclusive == 1) {
                        return fail(1017, "优惠券为新人专享,请重新选择");
                    }
                }
                //计算价格
                $payAmount = $payAmount - $couponAmount;
                if($payAmount <= 0){
                    return fail(1016,'订单错误');
                }
            }
            //计算运费
            $expressFeeData = ExpressConfig::where("amount","<=",$payAmount)->orderBy("amount","desc")->first();
            if ($expressFeeData){
                $payAmount = $payAmount+$expressFeeData->express_fee;
            }
            //查询公司副卡未使用的副卡
            $companyOilCardData = CompanyOilCard::where('status',0)->where("type",$type)->first();
            if (!$companyOilCardData)return fail(1030,"暂无可用的油卡");

            //查询该油卡是否重复
            $oilCardData = OilCard::where("card_no",$companyOilCardData->card_no)->where('status',1)->first();
            if ($oilCardData)return fail(1035,"亲!该油卡已被绑定,请及时更换哟!");

            //查询油卡商品
            $goodsData = Goods::where("class_id",0)->where("type_id",0)->first();
            if (!$goodsData)return fail(1021,"油卡商品未创建");

            //开启事务
            DB::beginTransaction();
            //绑定油卡
            $oil = new OilCard();
            $oil->user_id = $userData->id;
            $oil->card_no = $companyOilCardData->card_no;
            $oil->mobile = $addressData->phone;
            $oil->type = $companyOilCardData->type;
            $oil->name = $addressData->username;
            $oil->status = 0;
            $oil->is_company_card = 1;
            $oil->save();

            //修改公司油卡绑定情况
            $companyOilCardData->status = 1;
            $companyOilCardData->user_id = $userId;
            $companyOilCardData->used_at = Carbon::now();
            $companyOilCardData->save();

            //创建油卡商品订单
            $shopOrder = new ShopOrder();
            $shopOrder->order_sn = orderSn();
            $shopOrder->user_id = $userId;
            $shopOrder->goods_amount = $payAmount;
            $shopOrder->order_amount = $payAmount;
            $shopOrder->pay_amount = $payAmount;
            $shopOrder->coupon_id = 0;
            $shopOrder->username = $addressData->username;
            $shopOrder->phone = $addressData->phone;
            $shopOrder->address = $addressData->province.$addressData->city.$addressData->district.$addressData->address;
            $shopOrder->order_time = Carbon::now();
            $shopOrder->order_type = "oil_card";
            $shopOrder->order_status = 0;
            $shopOrder->save();

            $orderSn = orderSn();;
            //实例化对象
            $order = new RechargeOrder();
            $order->order_sn = $orderSn;
            $order->user_id = $userData->id;
            $order->recharge_id = $rechargeId;
            $order->coupon_id = $coupon_id;
            $order->type = 1;
            $order->recharge_amount = $amount;
            $order->pay_amount = $payAmount;
            $order->oil_card_id = $oil->id;
            $order->discount = $rechargeData->discount;
            $order->months = $rechargeData->months;
            $order->user_mobile = $userData->mobile;
            $order->card_type = $companyOilCardData->type;
            $order->card_no = $companyOilCardData->card_no;
            $order->status = 0;
            $order->recharge_mode = 2;
            $order->shop_order_id = $shopOrder->id;
            $order->created_at = Carbon::now();

            //收货地址
            $address = str_replace(',','',$addressData->city.$addressData->address);
            //记录油卡物流
//            $express = new OilCardExpress();
//            $express->order_sn = $orderSn;
//            $express->user_id = $userId;
//            $express->oil_card_no = $companyOilCardData->card_no;
//            $express->username = $addressData->username;
//            $express->phone = $addressData->phone;
//            $express->address = $address;
//            $express->express_fee = $expressFeeData->express_fee;
//            $express->created_at = Carbon::now();
//            $express->save();

            //创建油卡订单商品详细表
            $goodsOrder = new ShopOrderDetail();
            $goodsOrder->order_id = $shopOrder->id;
            $goodsOrder->order_sn = $shopOrder->order_sn;
            $goodsOrder->goods_id = $goodsData->id;
            $goodsOrder->class_id = $goodsData->class_id;
            $goodsOrder->class_name = $goodsData->class_name;
            $goodsOrder->goods_name = $companyOilCardData->card_no;
            $goodsOrder->image = 46708;
            $goodsOrder->sku_id = 0;
            $goodsOrder->created_at = Carbon::now();
            $goodsOrder->save();


            //创建支付
            $pay = new Pay();
            $pay->payment_method = $pay_type;
            $pay->user_id = $userData->id;
            $pay->pay_sn = Pay::makeYouKaPaySN();
            $pay->amount = $payAmount;
            $pay->save();

            $order->pay_id = $pay->id;//支付流水id
            $order->save();

            $response = [
                'order_id' => $order->id,
                'payment_method' => $pay_type,
                'pay_info' => null,
            ];
            $response['pay_info'] = '';
            $response['weixin_app'] = null;
            if ($pay_type == 'alipay') {
                $response['pay_info'] = Pay::alipay($pay);
            }
            if ($pay_type == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp($pay);
            }
            if ($pay_type == 'weixin') {
                $response['weixin'] = Pay::weixin($pay, $openid);
            }

            DB::commit();
            return success($response);

        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统异常");
        }
    }

    /*
    //查询订单
    public static function oilOrderList($page,$size,$userId,$status,$orderType){
        try{
            if ($status=='all'){
                if ($orderType=='oidcard') {
                    $orderData = RechargeOrder::where("user_id", $userId)->forPage($page, $size)->orderBy('id', 'desc')->get();
                }else{
                    $orderData = MobileRechargeOrder::where("user_id",$userId)->forPage($page,$size)->orderBy('id','desc')->get();
                }
                $order = [];
                if ($orderData->count()>0) {
                    foreach ($orderData as $item) {
                        if ($item->type==1){
                            $title = $item->recharge_amount.'元即使充值';
                        }else{
                            $title = $item->recharge_amount.'元'.$item->months.'个月套餐充值';
                        }
                        $order[] = ["id"=>$item->id,"title"=>$title,"amount"=>$item->recharge_amount,"status"=>$item->status,"created_at"=>$item->created_at];
                    }
                }
                return success($order);
            }elseif ($status==-1 || $status==0 || $status==1 || $status==2 || $status==3){
                if ($orderType=='oilcard') {
                    $orderData = RechargeOrder::where(function ($query) use ($userId, $status) {
                        $query->where("user_id", $userId)->where("status", $status);
                    })->forPage($page, $size)->orderBy("id", "desc")->get();
                }else{
                    $orderData = MobileRechargeOrder::where(function ($query) use ($userId, $status) {
                        $query->where("user_id", $userId)->where("status", $status);
                    })->forPage($page, $size)->orderBy("id", "desc")->get();
                }
                $order = [];
                if ($orderData->count()>0) {
                    foreach ($orderData as $item) {
                        if ($item->type==2){
                            $title = $item->recharge_amount.'元即时充值';
                        }else{
                            $title = $item->recharge_amount.'元'.$item->months.'个月套餐充值';
                        }
                        $order[] = ["id"=>$item->id,"title"=>$title,"amount"=>$item->pay_amount,"status"=>$item->status,"created_at"=>$item->created_at];
                    }
                }
                return success($order);
            }else{
                return fail(1003,"不合法的参数值:status");
            }

        }catch (\Exception $e){
            Log::error($e);
            return fail(500,"系统错误");
        }
    }

    //订单详情
    public static function oilOrderDetail($orderId,$userId,$orderType){
        try{
            $order = [];
            $orderData = [];
            $mobile = '';
            if ($orderType=='oilcard') {
                //查询订单
                $orderData = RechargeOrder::where("id",$orderId)->with('oilCard')->first();
            }
            if($orderType=='mobile'){
                $orderData = MobileRechargeOrder::where("id",$orderId)->first();
                if ($orderData)$mobile = $orderData->mobile;
            }
            if ($orderData){
                //待充值
                $stayAmount = 0;
                $detail = [];
                $title = '';
                if ($orderData->type==2){
                    $title = $orderData->recharge_amount."元即时充值";
                }else{
                    $orderDetailData = [];
                    if ($orderType=='oilcard'){
                        $title = $orderData->months.'个月油卡充值套餐';
                        //充值详情
                        $orderDetailData = RechargeOrderDetail::where("recharge_order_id",$orderData->id)->orderBy('pay_at','asc')->get();
                    }
                    if($orderType=='mobile'){
                        $title = $orderData->months.'个月手机充值套餐';
                        $orderDetailData = MobileRechargeOrderDetail::where("recharge_order_id",$orderData->id)->orderBy('pay_at','asc')->get();
                    }
                    if ($orderDetailData->count()>0){
                        $i = 1;
                        foreach ($orderDetailData as $item){
                            if ($item->result_status==0){
                                //计算待支付金额
                                $stayAmount += $item->amount;
                                $status = '('.$i.'/'.$orderData->months.'期)未到账';
                            }elseif($item->result_status==1){
                                $status = '('.$i.'/'.$orderData->months.'期)已到账';
                            }else{
                                $status = '('.$i.'/'.$orderData->months.'期)充值失败';
                            }
                            //添加到数组
                            $detail[] = ["amount"=>$item->amount,"pay_at"=>date('Y-m-d',strtotime($item->pay_at)),"status"=>$status];
                            $i++;
                        }
                    }
                }
                //支付方式
                $pay_method = "未支付";
                if ($orderData->pay_id) {
                    $payData = Pay::find($orderData->pay_id);
                    if ($payData){
                        if ($payData->payment_method=='weixin_app' || $payData->payment_method=='weixin') {
                            $pay_method = "微信";
                        }elseif ($payData->payment_method=="alipay"){
                            $pay_method = "支付宝";
                        }else{
                            $pay_method = "其他";
                        }
                    }
                }
                //查询优惠券
                $coupon = 0.00;
                if ($orderData->coupon_id){
                    $couponData = UserCoupon::find($orderData->coupon_id);
                    if ($couponData)
                        $coupon=$couponData->amount;
                }
                //查询订单明细
                $order = ['id'=>$orderData->id,"title"=>$title,"oil_card"=>$orderData->oilCard->card_no,"mobile"=>$mobile,"order_type"=>$orderType,"amount"=>$orderData->pay_amount,"content"=>$title,"coupon"=>$coupon,"stay_amount"=>(string)$stayAmount,"order_sn"=>$orderData->order_sn,"pay_method"=>$pay_method,"order_date"=>date('Y-m-d H:i:s',strtotime($orderData->created_at)),"detail"=>$detail];
            }
            return success($order);
        }catch (\Exception $e){
            Log::error($e);
            return fail(500,'系统错误');
        }
    }*/

}